import com.google.appengine.api.datastore.*
import static com.google.appengine.api.datastore.FetchOptions.Builder.*
import twitter4j.*
import twitter4j.http.*
import com.pobos.*


if (params.tweet && params.url) {
	tweet(params.tweet, params.url)
}

private String shortenUrl(url) {
	try {
		def result = urlFetch.fetch(new URL("http://is.gd/api.php?longurl=" + url))
		def shortened = (result.responseCode == 200 ? new String(result.content) : url)
		return shortened
	} catch (Exception e) {
		return url // epic fail...
	}
}

private void tweet(def tuit, def url) {
	try {
		def statusText =  "${tuit} - " + shortenUrl(url)
		if (statusText.size() > 140) {
			statusText = statusText[0..139]
		}
		println "Preparing to tweet: [${statusText}]"
		def query =  new Query(Constants.TWITTER_AUTH)
		PreparedQuery preparedQuery = datastore.prepare(query)
		def cred = preparedQuery.asList( withLimit(1) )
		if (cred) {
			println "Successfully retrieved twitter creds: ${cred[0].token} ${cred[0].tokenSecret}"
			def config = new Properties()
			config.load(Constants.class.getClassLoader().getResourceAsStream("config.properties"))
			Twitter twitter = new TwitterFactory().getInstance()
			twitter.setOAuthConsumer(config.consumer_key, config.consumer_secret)
			AccessToken accessToken = new AccessToken(cred[0].token, cred[0].tokenSecret)
			twitter.setOAuthAccessToken(accessToken)
			twitter.verifyCredentials()
			Status status = twitter.updateStatus(statusText)
			println "Successfully updated the status to [${status.text}]"
		} else {
			println "No twitter creds found, skipping tweet..."
		}
		
	} catch (Exception e) {
		println "Error tweeting status for ${tuit}: ${e}"
	}
}